package com.study.common;

import com.google.common.collect.Lists;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * spring上下文中对象获取工具类
 *
 * @author lemontree
 * @version 2.0, 2017/5/23
 * @since 2.0
 */
@Component
public class SpringContextHolder implements ApplicationContextAware {
    private static ApplicationContext context;

    public static ApplicationContext getContext() {
        return context;
    }

    public static <T> T  getBean(String beanName, Class<T> clazz) {
        return context.getBean(beanName, clazz);
    }

    public static <T> T getBean(Class<T> clazz) {
        return context.getBean(clazz);
    }

    public static <T> List<T> getBeans(Class<T> clazz) {
        Map<String, T> beans = context.getBeansOfType(clazz);
        if (Objects.isNull(beans)) {
            return null;
        }

        return Lists.newArrayList(beans.values());
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        context = applicationContext;
    }

}
